package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@Api(tags = "菜品管理")
@RequestMapping("admin/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    @ApiOperation("添加菜品和口味")
    @PostMapping()
    public Result saveWithFlavors(@RequestBody DishDTO dishDTO){
        String key = "dish_" + dishDTO.getCategoryId();
        cleanCache(key);
        dishService.saveWithFlavors(dishDTO);
        return Result.success();
    }
    @GetMapping("/page")
    @ApiOperation("分页查询")
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO){
        PageResult pageResult =dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @DeleteMapping
    @ApiOperation("批量删除菜品")
    public Result deleteDish(@RequestParam List<Long> ids){
        cleanCache("dish_*");
        dishService.deleteDish(ids);
        return Result.success();
    }

    @PostMapping("/status/{status}")
    @ApiOperation("设置菜品状态")
    public Result setStatus(@PathVariable Long status,Long id){
        cleanCache("dish_*");
        dishService.setStatus(status,id);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("查询菜品和口味")
    public Result<DishVO> getDish(@PathVariable Long id){
        DishVO dishVo =dishService.getDish(id);
        return Result.success(dishVo);
    }
    @PutMapping
    @ApiOperation("修改菜品")
    public Result updateDish(@RequestBody DishDTO dishDTO){
        cleanCache("dish_*");
        dishService.update(dishDTO);
        return Result.success();
    }

    @ApiOperation("根据分类id查询菜品")
    @GetMapping("/list")
    public Result getByCategoryID(Long categoryId){
        log.info("查询分类id为:{}的菜品",categoryId);
        List<Dish> dishes = dishService.getByCategoryId(categoryId);
        return Result.success(dishes);
    }

    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}


